import { Connection } from "./connection";
import { DbConnectionConfig } from "../../type/dbtype";

/**
 * mysql 配置
 */
export class mySqlDriver {
    /**
     * 配置
     */
    protected options: object;

    /**
     * 连接池
     */
    protected pool: any;

    /**
     * 数据库模块
     */
    protected dbMdl: any;
    /**
     * 构造器
     * @param cfg -   连接配置
     */
    constructor(cfg: DbConnectionConfig) {
        this.dbMdl = require('mysql');
        this.options = {
            host: cfg.host,
            user: cfg.user,
            password: cfg.password,
            database: cfg.database,
            usePool: cfg.usePool
            // connectionLimit: cfg.connectionLimit
        };
        //连接池
        if (cfg.usePool) {
            this.pool = this.dbMdl.createPool(this.options);
        }
    }

    /**
     * 获取连接
     */
    async getConnection(): Promise<any> {
        return new Promise((resolve, reject) => {
            if (this.pool) {
                this.pool.getConnection((err, conn) => {
                    if (err) {
                        return reject(err);
                    }
                    resolve(conn);
                })

            } else {
                const conn = this.dbMdl.createConnection(this.options);
                conn.connect(err => {
                    if (err) {
                        return reject(err);
                    }
                    resolve(conn);
                    console.log('not pool');

                });
            }
        });
    }

    /**
     * 关闭连接
     * @param connection 数据库连接对象
     */
    public async closeConnection(connection: Connection): Promise<void> {
        if (this.pool) {
            connection.conn.release();
            return Promise.resolve(null);
        } else {
            return new Promise((resolve, reject) => {
                connection.conn.end(err => {
                    if (err) {
                        return reject(err);
                    }
                    resolve(null);
                });
            });
        }
    }

    public async endPool() {
        if (this.pool) {
            new Promise((resovle, reject) => {
                this.pool.end(err => {
                    if (err) reject('连接池关闭错误');
                })
            })
        }
    }
}